<template>
  <el-dialog
    v-model="dialogShow"
    :title="option.type == 'add' ? '新增数据源' : '编辑数据源'"
    width="30%"
    @open="open"
    @close="close"
  >
    <el-form class="d-form" :mode="form" label-width="120">
      <el-form-item label="数据源编号">
        <el-input
          v-model="form.dataSourceCode"
          placeholder="数据源编号"
          :readonly="option.type == 'edit'"
        ></el-input>
      </el-form-item>
      <el-form-item label="连接信息">
        <el-input
          v-model="form.connectionInfos"
          placeholder="连接信息"
        ></el-input>
      </el-form-item>

      <el-form-item label="数据类型" placeholder="数据类型">
        <el-select v-model="form.dataSoureType">
          <el-option
            v-for="item of option.typeArray"
            :Key="item.value"
            :value="item.value"
            :label="item.label"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item class="btns">
        <el-button type="primary" @click="save">确 认</el-button>
        <el-button type="primary" @click="cancel">取 消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { computed, reactive } from "vue"
import { postDataSource, putDataSource } from "../../../api/dataSource.js"
import { ElMessage } from "element-plus"

let props = defineProps({
  dataShow: {
    type: Boolean,
    default: false,
  },
  option: {
    type: Object,
    default: () => {
      return {
        type: "add",
        data: {},
        typeArray: [],
      }
    },
  },
})
let emit = defineEmits(["data-close"])

let form = reactive({
  connectionInfos: "",
  dataSourceCode: "",
  dataSoureType: "",
})
let dialogShow = computed(() => {
  return props.dataShow
})

async function save() {
  if (props.option.type == "add") {
    let res = await postDataSource(form)
    if (res.status) {
      ElMessage.success("添加成功")
      emit("data-close", true)
    } else {
      ElMessage.error(res.message || "添加失败")
    }
  } else {
    let res = await putDataSource(form.dataSourceCode, form)
    if (res.status) {
      ElMessage.success("修改成功")
      emit("data-close", true)
    } else {
      ElMessage.error(res.message || "修改失败")
    }
  }
}

function cancel(val = false) {
  for (let key in form) {
    form[key] = ""
  }
  emit("data-close", val)
}

function open() {
  if (props.option.type == "edit") {
    for (let key in form) {
      form[key] = props.option.data[key] ?? ""
    }
  }
}

function close() {
  emit("data-close")
}
</script>
<style scoped lang="scss">
.d-form {
  width: 100%;

  .el-select {
    width: 100%;
  }
  .btns {
    :deep(.el-form-item__content) {
      justify-content: flex-end;
    }
  }
}
</style>
